
package com.winning.sx.microframework.controller.base;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.winning.dapi.data.entity.DataTable;
import com.winning.sx.microframework.common.util.BaseUtil;
import com.winning.sx.microframework.common.util.Constains;
import com.winning.sx.microframework.common.util.EncryptionUtil;
import com.winning.sx.microframework.model.exception.CustomException;
import com.winning.sx.microframework.model.message.AjaxDataResponseMessage;
import com.winning.sx.microframework.model.message.AjaxTableResponseMessage;
import com.winning.sx.microframework.service.EasyService;
import com.winning.sx.microframework.service.sysmanage.UserNewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/inner/staff")
public class InnerStaffController {
    @Autowired
    EasyService easyService;
    @Autowired
    UserNewService service;

    @RequestMapping(value = {"/", ""})
    public ModelAndView init() throws IOException, CustomException {
        ModelAndView mv = new ModelAndView("/base/inner");
        return mv;
    }

    // 客户机构管理查询
    @ResponseBody
    @RequestMapping(value = {"/queryList"})
    public AjaxTableResponseMessage queryMessageList(String datas) {
        AjaxTableResponseMessage ajaxTableResponseMessage = new AjaxTableResponseMessage();
        Map<String, String> param = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null)
                param = objectMapper.readValue(datas, Map.class);
            String staffInformation=param.get("staffInformation");
            String oid=param.get("organizationId");
            Map paramSql=new HashMap();
            if(oid!=null&&oid.length()>=1){
                paramSql.put("organizationId",oid);
            }
            if(staffInformation.length()==11){
                paramSql.put("telephone",param.get("staffInformation"));
            }else {
                if (staffInformation.length() <= 0) {
                    paramSql.put("telephone",null);
                    paramSql.put("name",null);
                } else {
                    paramSql.put("name", param.get("staffInformation"));
                }
            }
            String sql="select *,r.cRoleName  from BASE_Staff s left join PM_ROLES r on r.cRoleID=s.role" +
                    "  where s.organizationId in ( " +

                    " select id from BASE_Organization o where 1=1" +

                    (paramSql.get("organizationId") != null ? " and o.id=:organizationId or o.superOrganizationId=:organizationId "  : "")+
                    "and organizationType='400002') " +
                    (paramSql.get("telephone") != null ? (" and s.telephone=" +"'"+ paramSql.get("telephone"))+"'" : "")+
                    (paramSql.get("name") != null ? (" and s.name=" +"'"+ paramSql.get("name"))+"'" : "")+
                    " order by s.createTime desc";
            DataTable all = easyService.querySql(sql,paramSql);
            ajaxTableResponseMessage.setDatas(all.getDataRows());
            ajaxTableResponseMessage.setTotalSize((int) all.getTotalRowNum());
            ajaxTableResponseMessage.setSuccess(true);
        } catch (Exception e) {
            ajaxTableResponseMessage.setSuccess(false);
            ajaxTableResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxTableResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/save"})
    public AjaxDataResponseMessage insert(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                Map mapNew = new HashMap();
                String staffId = null;
                if (!"".equals(map.get("role")) && map.containsKey("role") == true) {
                    mapNew.put("role", map.get("role"));
                    //根据手机号判断是否存在该员工
                    Map staffParam = new HashMap();
                    staffParam.put("telephone", map.get("telephone"));
                    Map staffEntity = easyService.queryEntity("BASE_Staff", staffParam);
                    if (staffEntity == null) {
                        map.put("state","200001");
                        map.put("validState", Constains.SYS_VALIDFLAG_TRUE);
                        map.put("validCode",createValCode(6));
                        easyService.save("BASE_Staff", "id", map);
                        staffId = map.get("id").toString();
                        //将信息插入用户表
                        Map userParam = new HashMap();
                        userParam.put("cUserID", BaseUtil.createUUID());
                        userParam.put("cPassword", EncryptionUtil.getHash("123456"));
                        userParam.put("cUserCode", map.get("telephone"));
                        userParam.put("cUserName", map.get("name").toString());
                        userParam.put("bState", "True");
                        service.insert("PM_USERS", userParam);
                        String cUserID = userParam.get("cUserID").toString();
                        //将信息插入员工用户关联表
                        Map relaUserStaff = new HashMap();
                        relaUserStaff.put("userId", cUserID);
                        relaUserStaff.put("staffId", staffId);
                        service.insertRela("PM_StaffAsUser", relaUserStaff);
                        //将信息插入用户角色表
                        String roleId = mapNew.get("role").toString();
                        Map relaRoleUser = new HashMap();
                        relaRoleUser.put("cUserID", cUserID);
                        relaRoleUser.put("cRoleID", roleId);
                        service.insertRela("PM_UserAsRole", relaRoleUser);
                    } else {
                        //表中存在此员工，修改此员工的信息
                        staffId = staffEntity.get("id").toString();
                        Map paramNew = new HashMap();
                        paramNew.put("id", staffId);
                        map.remove("id");
                        easyService.update("BASE_Staff", paramNew, map);
                        //通过员工id找到关联表对应的用户id
                        Map staffAsUser = new HashMap();
                        staffAsUser.put("staffId", staffId);
                        Map staffAsUserEntity = service.queryEntity("PM_StaffAsUser", staffAsUser);
                        if (staffAsUserEntity != null) {
                            //先找到用户然后更新该用户下的角色
                            Map userParam = new HashMap();
                            userParam.put("cUserID", staffAsUserEntity.get("userId"));
                            Map userNewParam=new HashMap();
                            userNewParam.put("cUserCode", map.get("telephone"));
                            userNewParam.put("cUserName", map.get("name").toString());
                            easyService.update("PM_USERS",userParam,userNewParam);
                            Map userAsRoleEntity = easyService.queryEntity("PM_UserAsRole", userParam);
                            if (userAsRoleEntity != null) {
                                Map roleNew = new HashMap();
                                roleNew.put("cRoleID", mapNew.get("role"));
                                easyService.update("PM_UserAsRole", userParam, roleNew);
                            }
                        }
                    }
                }else if("".equals(map.get("role"))||map.get("role")==null&& !"".equals(map.get("id").toString())){
                    Map paramId=new HashMap();
                    paramId.put("id",map.get("id").toString());
                    map.remove("id");
                    easyService.update("BASE_Staff",paramId,map);
                    Map paramStaff = new HashMap();
                    paramStaff.put("staffId",paramId.get("id").toString());
                    Map relaEntity=easyService.queryEntity("PM_StaffAsUser",paramStaff);
                    if(relaEntity!=null){
                        Map paramUser=new HashMap();
                        paramUser.put("cUserID",relaEntity.get("userId").toString());
                        Map paramUserState=new HashMap();
                        paramUserState.put("validFlag","100002");
                        paramUserState.put("bState","False");
                        easyService.update("PM_USERS",paramUser,paramUserState);
                    }
                }
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }
    @ResponseBody
    @RequestMapping(value = {"/password"})
    public AjaxDataResponseMessage password(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                    Map param = new HashMap();
                    String id=map.get("id");
                    param.put("id",id );
                    Map staffEntity = easyService.queryEntity("BASE_Staff", param);
                    if (staffEntity != null) {
                        Map staffParam=new HashMap();
                        String roleName=staffEntity.get("role").toString();
                        staffParam.put("cRoleName",roleName );
                        Map roleEntity=easyService.queryEntity("PM_ROLES",staffParam);
                        if(roleEntity!=null){
                            Map roleParam=new HashMap();
                            String roleId=roleEntity.get("cRoleID").toString();
                            roleParam.put("cRoleID",roleId);
                            Map relaEntity=easyService.queryEntity("PM_UserAsRole",roleParam);
                            if(relaEntity!=null){
                                Map relaParam=new HashMap();
                                String userId=relaEntity.get("cUserID").toString();
                                relaParam.put("cUserID",userId);
                               Map userEntity=easyService.queryEntity("PM_USERS",relaParam);
                                if(userEntity!=null){
                                    Map userParam=new HashMap();
                                    String userid=userEntity.get("cUserID").toString();
                                    userParam.put("cUserID",userid);
                                    Map userP=new HashMap();
                                    userP.put("cPassword","E10ADC3949BA59ABBE56E057F20F883E");
                                   easyService.update("PM_USERS",userParam,userP);
                                }
                            }
                        }
                    }
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }

    @ResponseBody
    @RequestMapping(value = {"/delete"})
    public AjaxDataResponseMessage delete(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                easyService.delete("BASE_Staff", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }
    //验证码
    @ResponseBody
    @RequestMapping(value = {"/editYZM"})
    public AjaxDataResponseMessage editYZM(String datas) {
        AjaxDataResponseMessage ajaxDataResponseMessage = new AjaxDataResponseMessage();
        Map<String, String> map = null;
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            if (datas != null) {
                map = objectMapper.readValue(datas, Map.class);
                map.put("validState",Constains.SYS_VALIDFLAG_TRUE);
                map.put("validCode",createValCode(6));
                easyService.save("BASE_Staff", "id", map);
                ajaxDataResponseMessage.setSuccess(true);
            }
        } catch (Exception e) {
            ajaxDataResponseMessage.setSuccess(false);
            ajaxDataResponseMessage.setErrorMsg("操作失败：" + e.getMessage());
        }
        return ajaxDataResponseMessage;
    }
    public static String createValCode(int length) {
        String validateCode = "";
        for (int i = 0; i < length; i++) {
            validateCode += String.valueOf(Math.round(Math.random() * 8 + 1));
        }
        return validateCode;
    }
}

